package com.howie.gulimall.product.service.impl;

import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.howie.common.constant.ProductConstant;
import com.howie.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.howie.gulimall.product.dao.AttrGroupDao;
import com.howie.gulimall.product.dao.CategoryDao;
import com.howie.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.howie.gulimall.product.entity.AttrGroupEntity;
import com.howie.gulimall.product.entity.CategoryEntity;
import com.howie.gulimall.product.service.CategoryService;
import com.howie.gulimall.product.vo.AttrResponseVo;
import com.howie.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.howie.common.utils.PageUtils;
import com.howie.common.utils.Query;

import com.howie.gulimall.product.dao.AttrDao;
import com.howie.gulimall.product.entity.AttrEntity;
import com.howie.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    private AttrAttrgroupRelationDao relationDao;
    @Resource
    private AttrGroupDao attrGroupDao;
    @Resource
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);

        /*attrEntity.setAttrName(attrVo.getAttrName());
        attrEntity.setSearchType(attrVo.getSearchType());
        attrEntity.setIcon(attrVo.getIcon());
        attrEntity.setValueSelect(attrVo.getValueSelect());
        attrEntity.setAttrType(attrVo.getAttrType());
        attrEntity.setEnable(attrVo.getEnable());
        attrEntity.setCatelogId(attrVo.getCatelogId());
        attrEntity.setShowDesc(attrVo.getShowDesc());*/

        // 1、保存基本数据
        this.save(attrEntity);
        // 2、保存关联关系
        if(attrVo.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        // 如果是基本属性(规格参数) type 就等于1,否则等于0(销售属性)。这里使用枚举类表示，方便维护
        Integer type = "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("attr_type",type);
        if(catelogId != 0){
            // select * from `pms_attr` where catelog_id = ?
            wrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key"); // 获取检索关键字
        if(StringUtils.isNotEmpty(key)){
            // attr_id  attr_name
            wrapper.and((tempWrapper) -> {
                // and attr_id = ? or attr_name like '%' ? '%'
                tempWrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        // AttrEntity与AttrResponse做一个映射
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> responseVos = records.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            // 我们还要设置分类名字(catelogName)和分组名字(groupName)
            AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId())); // 根据attr_id查询出一条AttrAttrgroupRelationEntity
            // 设置分组信息(注意销售属性没有分组信息)
            if(type.equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
                if (entity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(entity.getAttrGroupId());
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            // 设置分类信息
            if(attrEntity.getCatelogId() != null){
                CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        pageUtils.setList(responseVos);
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrResponseVo);

        // 1、设置分组信息：在关联关系表中根据attrId查询出分组id(attrGroupId)
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            AttrAttrgroupRelationEntity entity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if(entity != null){
                attrResponseVo.setAttrGroupId(entity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(entity.getAttrGroupId());
                if(attrGroupEntity != null){
                    attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 2、设置分类信息：查找分类id，根据分类id查找出完整分类路径
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrResponseVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if(categoryEntity != null){
            attrResponseVo.setAttrName(categoryEntity.getName());
        }
        return attrResponseVo;
    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.updateById(attrEntity);

        // 更新关联信息
        if(attrEntity.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode())){
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attrVo.getAttrGroupId());
            entity.setAttrId(attrVo.getAttrId());

            UpdateWrapper<AttrAttrgroupRelationEntity> wrapper = new UpdateWrapper<>();
            wrapper.eq("attr_id",attrVo.getAttrId());
            if(count > 0){
                // 1、修改分组关联
                relationDao.update(entity,wrapper);
            }else{
                // 2、添加分组关联
                relationDao.insert(entity);
            }
        }
    }
    /**
     * @description: 根据分组id查询关联的所有基本属性
     * @author: laizhenghua
     * @date: 2020/12/21 17:43
     * @param: attrgroupId
     * @return: java.util.List<com.howie.gulimall.product.entity.AttrEntity>
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        // 1、在关联关系表(pms_attr_attrgroup_relation)中通过属性分组id查询出所有attr的id
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_group_id",attrgroupId);
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(wrapper);
        // entity：list里的元素
        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        // 2、非空判断
        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        // 3、通过attr的id查询attr
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    /**
     * @description: 获取当前分组没有关联的属性
     * @author: laizhenghua
     * @date: 2020/12/23 19:49
     * @param: attrgroupId
     * @param: params
     * @return: com.howie.common.utils.PageUtils
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        // 1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2、当前分组只能关联别的分组没有引用的属性
        /*
        2.1、当前分类的其他分组
        2.2、这些分组关联的属性
        2.3、从当前分类的所有属性中移除这些属性
        */
        List<AttrGroupEntity> groups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));

        List<Long> attrgroupIds = groups.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", attrgroupIds));

        List<Long> attrIds = relationEntities.stream().map(AttrAttrgroupRelationEntity::getAttrId)
                .collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if(attrIds != null && attrIds.size() > 0){
            wrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((w) -> {
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> getEnableSearchAttrIds(List<Long> attrIds) {
        // SELECT attr_id FROM `pms_attr` WHERE attr_id IN(?) AND attr_type = 1;
        return this.baseMapper.selectEnableSearchAttrIds(attrIds);
    }
}